<?php

namespace app\controller\api;

use app\model\api\ah\SkzyCamp;
use app\model\api\ah\AhAmuletLevel;
use app\model\api\ah\AhCareer;
use app\model\api\ah\AhCoordinate;
use app\model\api\ah\AhEquipment;
use app\model\api\ah\AhEquipmentAttributes;
use app\model\api\ah\AhGemstone;
use app\model\api\ah\AhLabel;
use app\model\api\ah\AhOutfit;
use app\model\api\ah\AhOutfitPlayStyle;
use app\model\api\ah\AhPlayStyle;
use app\model\api\ah\AhSkill;
use app\model\api\ah\XmUser;
use app\model\api\ah\XmUserCollect;
use app\model\api\ah\XmUserLikes;
use app\service\api\AhService;
use app\service\ConfServiceFacade;
use laytp\controller\Api;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * Class Ah
 * @package app\index\controller
 */
class Ah extends Api
{
    private $career_model;
    private $coordinate_model;
    private $equipment_model;
    private $equipment_attributes_model;
    private $gemstone_model;
    private $play_style_model;
    private $skill_model;
    protected $xm_user_model;
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 获取首页搜索数据
     * @return false|string|\think\response\Json
     */
    public function indexConfig()
    {
        try {
            $this->career_model = new AhCareer();
            $this->play_style_model = new AhPlayStyle();
            $career = $this->changeData($this->career_model->cache(true)->select()->toArray(), ['create_time']);
            $img = imgUrlToAbsolute("/20220805/417dd141ade56830bd9c553a9f3c2b6d.png");
            array_unshift($career,[
               'id' => '',
               'name'=>'全部角色',
               'avatar'=>$img,
               'picture'=>$img,
               'role_id'=>$img,
            ]);
            $play_style = $this->changeData($this->play_style_model->cache(true)->order('sort desc')->select()->toArray(), ['create_time']);
            array_unshift($play_style,[
                'id'=>'',
                'name'=>'全部',
                'sort'=>999
            ]);
            return $this->success('success', compact("career", "play_style"));
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }


    /**
     * 获取首页搜索数据
     * @return false|string|\think\response\Json
     */
    public function indexList(AhService $ahService)
    {
        try {
            $data = input('post.');
            //验证器
            validate(\app\validate\api\Ah::class)
                ->scene('list')
                ->check($data);
            $list  = $ahService->indexList($data);
            return $this->success('success', $list['data'], array(
                'total' => $list['total'],
                'current_page' => $list['current_page'],
                'last_page' => $list['last_page'],
                'per_page' => $list['per_page'],
            ));

        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 收藏/取消收藏操作
     * @return false|string|\think\response\Json|void
     * @throws \think\db\exception\DbException
     */
    public function userCollect()
    {
        $data = input('post.');
        $model = new AhOutfit();
        $collect_model = new XmUserCollect();
        //验证器
        validate(\app\validate\api\Ah::class)
            ->scene('collect')
            ->check($data);
        $count = $collect_model ->cache(true)->where('user_id', $data['user_id'])->where('outfit_id', $data['outfit_id'])->count();
        switch ($data['action']) {
            case "yes":
                if ($count > 0) {
                    return $this->error("您已收藏该配装");
                }
                $collect_model->insert([
                    'user_id' => $data['user_id'],
                    'outfit_id' => $data['outfit_id'],
                ]);
                $this->clearCache();
                return $this->success('收藏成功');
            case "no":
                if ($count == 0) {
                    return $this->error("您未收藏该配装");
                }
                $collect_model->where('user_id',$data['user_id'])->where('outfit_id', $data['outfit_id'])->delete();
                $this->clearCache();
                return $this->success('取消收藏成功');
        }
    }

    /**
     * 发布/取消发布操作
     * @return false|string|\think\response\Json|void
     */
    public function userPublish()
    {
        $data = input('post.');
        $model = new AhOutfit();
        //验证器
        validate(\app\validate\api\Ah::class)
            ->scene('publish')
            ->check($data);
        $upData  = ['is_publish' => $data['action']];
        if($data['action']=='no'){
            $upData['label_id'] = 0;
            $upData['is_recommend'] = 'no';
        }
        $model
            ->where('user_id', $data['user_id'])->where('id', $data['outfit_id'])->save($upData);
        switch ($data['action']) {
            case 'yes':
                $this->clearCache();
                return $this->success('发布成功');
            case'no':
                $this->clearCache();
                return $this->success('取消发布成功');
        }
    }

    /**
     * 添加配装操作
     * @return false|string|\think\response\Json
     * @throws \Exception
     */
    public function addOutfit()
    {
        $data = input('post.');
        $model  = new AhOutfit();
        $play_model = new AhOutfitPlayStyle();
        try {
            //验证器
            validate(\app\validate\api\Ah::class)
                ->scene('add')
                ->check($data);
            if (!isset($data['role_id']) || $data['role_id'] == '') {
                return $this->error("请选择角色");
            }
            //验证是否有重名字的操作
            if($model->where('user_id',$data['user_id'])->where('name',$data['name'])->count()>0){
                return $this->error('您提交的配装名称重复');
            }

            $this->xm_user_model = new XmUser();
            //存储小米用户信息
            if(!$this->xm_user_model->checkUser([
                'user_id'=>$data['user_id'],
                'nickname'=>$data['nickname'],
                'avatar'=>$data['avatar'],
            ])){return $this->error('更新用户信息失败');};
            $data['detail'] = json_encode($data['detail'], 256);
            $data['create_time'] = date("Y-m-d H:i:s");
            $data['update_time'] = date("Y-m-d H:i:s");
            Db::startTrans();
            $id = $model->strict(false)->insertGetId($data);
            $play_ids = [];
            if (!isset($data['play_style_id'])) {
                return $this->error("请选择玩法");
            }
            foreach ($data['play_style_id'] as $v) {
                $play_ids[] = [
                    'play_style_id' => $v,
                    'outfit_id' => $id,
                ];
            }
            if (count($play_ids) > 0) $play_model->saveAll($play_ids);
            DB::commit();
            $this->clearCache();
            return $this->success('添加配装成功');
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception);
        }
    }

    /**
     * 编辑配装操作
     * @return false|string|\think\response\Json
     * @throws \Exception
     */
    public function editOutfit()
    {
        $data = input('post.');
        try {
            //验证器
            validate(\app\validate\api\Ah::class)
                ->scene('edit')
                ->check($data);
            $model = new AhOutfit();
            $this->xm_user_model = new XmUser();
            $play_model = new AhOutfitPlayStyle();
            if (!isset($data['role_id']) || $data['role_id'] == '') {
                return $this->error("请选择角色");
            }
            if (!isset($data['play_style_id'])) {
                return $this->error("请选择玩法");
            }
            //验证是否有重名字的操作
            if($model->where('user_id',$data['user_id'])->whereNotIn('id',[$data['outfit_id']])->where('name',$data['name'])->count()>0){
                return $this->error('您提交的配装名称重复');
            }
            //存储小米用户信息
            if(!$this->xm_user_model->checkUser([
                'user_id'=>$data['user_id'],
                'nickname'=>$data['nickname'],
                'avatar'=>$data['avatar'],
            ])){return $this->error('更新用户信息失败');};
            $data['detail'] = json_encode($data['detail'], 256);
            Db::startTrans();
            $play_style_id = $data['play_style_id'];
            $id = $data['outfit_id'];
            unset($data['play_style_id']);
            unset($data['outfit_id']);
            if(!isset($data['attr'])){
                $data['attr'] = '';
            }
            if(!isset($data['is_publish'])){
                $data['is_publish'] = 'no';//发布状态
            };
            $model->where('id', $id)->save([
                'user_id'=>$data['user_id'],
                'name'=>$data['name'],
                'role_id'=>$data['role_id'],
                'description'=>$data['description'],
                'detail'=>$data['detail'],
                'attr'=> $data['attr'],
                'is_publish'=> $data['is_publish'],
            ]);
            $play_model->destroy(function ($query) use ($id) {
                return $query->where('outfit_id', $id);
            });
            $play_ids = [];
            foreach ($play_style_id as $v) {
                $play_ids[] = [
                    'play_style_id' => $v,
                    'outfit_id' => $id,
                ];
            }
            if (count($play_ids) > 0) $play_model->saveAll($play_ids);
            Db::commit();
            $this->clearCache();
            return $this->success('編輯配装成功');
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception);
        }
    }

    /**
     * 配装详情页面
     * @return false|string|\think\response\Json
     */
    public function detailOutfit(AhService $ahService)
    {
        $data = input('post.');
        try {
            //验证器
            validate(\app\validate\api\Ah::class)
                ->scene('detail')
                ->check($data);
            $item = $ahService->detailOutfit($data);

            return $this->success('success', compact('item'));
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    public function addLikesNumber()
    {
        $data = input('post.');
        try {
            if (!isset($data['outfit_id']) || $data['outfit_id'] == '') {
                return $this->error("请选择配装");
            }
            if (!isset($data['user_id']) || $data['user_id'] == '') {
                return $this->error("缺少用户信息");
            }
            $model = new AhOutfit();
            $likes_model = new XmUserLikes();
            if($likes_model->cache(true)->where('user_id',$data['user_id'])->where('outfit_id',$data['outfit_id'])->count()>0){
                return $this->error('您已经点赞');
            }
            $number = $model->cache(true)->where('id', $data['outfit_id'])->value("likes_number");
            if ($number===false) {
                return $this->error('配装不存在');
            }
            $number = $number + 1;
            $model->where('id', $data['outfit_id'])->save(['likes_number' => $number]);
            $likes_model->save(['user_id'=>$data['user_id'],'outfit_id'=>$data['outfit_id']]);
            $this->clearCache();
            return $this->success('success',['number'=>$number]);
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 获取职业技能
     * @return false|string|\think\response\Json
     */
    public function careerSkills()
    {
        $this->skill_model = new AhSkill();
        $data = input('post.');
        if (!isset($data['role_id']) || $data['role_id'] == '') {
            return $this->error("请选择职业");
        }
        try {
            $list = $this->changeData(
                $this->skill_model->where('role_id', $data['role_id'])->cache(true)->select()->toArray(),
                ['create_time', 'kind'],
                ['tags']
            );
            $attack = [];
            $skill = [];
            foreach ($list as $value) {
                if ($value['type'] == 2) {
                    unset($value['type']);
                    $attack[] = $value;
                } elseif ($value['type'] == 1) {
                    unset($value['type']);
                    $skill[] = $value;
                }
            }
            return $this->success('success', compact('skill', 'attack'));
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    public function careersCoordinates()
    {
        $this->coordinate_model = new AhCoordinate();
        try {
            $list = $this->changeData(
                $this->coordinate_model->with(['equipments'])->withCache(30)->cache(true)->select()->toArray(),
                ['id', 'create_time']
            );
            $list = array_map(function ($item) {
                $item['equipments'] =  array_map(function ($i) {
                    return [
                        "id" => $i['id'],
                        "name" => $i['name'],
                        "equip_id" => $i['equip_id'],
                        "icon" => $i['icon'],
                        "rarity" => $i['rarity'],
                        "kind" => $i['kind'],
                        "kind_desc" => $i['kind_desc'],
                        "level_limit" => $i['level_limit'],
                        "score" => $i['score'],
                        "description" => $i['description'],
                        "attr_name" => $i['attr_name'],
                        "attr_value" => $i['attr_value'],
                        "coordinate_id" => $i['coordinate_id'],
                    ];
                }, $item['equipments']);
                return $item;
            }, $list);
            return $this->success('success', compact('list'));
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 职业装备
     * @return false|string|\think\response\Json
     */
    public function careersEquipment()
    {
        $this->career_model = new AhCareer();
        $this->equipment_model = new AhEquipment();
        $data = input('post.');
        $careers = $this->career_model->cache(true)->select()->toArray();
        $careers = array_combine(array_column($careers, 'role_id'), array_column($careers, 'name'));
        if (!isset($data['role_id']) || $data['role_id'] == '') {
            return $this->error("请选择职业");
        }
        try {
            $where = [];
            $where[] = ['role_id', 'like', "%" . $data['role_id'] . "%"];
            if (isset($data['kind']) && $data['kind'] != '') {
                $where[] = ['kind', '=', $data['kind']];
            }
            $list = $this->changeData(
                $this->equipment_model->with(['coordinate', 'coordinates'])->withCache(30)->cache(true)->where($where)->select()->toArray(),
                ['create_time',],
                ['role_id']
            );
            foreach ($list as &$v) {
                $v['role_name'] = [];
                foreach ($v['role_id'] as $i) {
                    if (isset($careers[$i])) $v['role_name'][] = $careers[$i];
                }
                if (!empty($v['coordinate'])) $v['coordinate'] = [
                    'coordinate_id' => $v['coordinate']['coordinate_id'],//套装id
                    'name' => $v['coordinate']['name'],//套装名称
                    'attr1' =>$v['coordinate']['attr1'],//套装属性1
                    'attr2' => $v['coordinate']['attr2'],//套装属性2
                    'attr3' => $v['coordinate']['attr3'],//套装属性3
                    'coordinates' => array_map(function ($item) {
                        return [
                            'id' => $item['id'],
                            'name' => $item['name'],
                            'equip_id' => $item['equip_id'],
                        ];
                    }, $v['coordinates'])
                ];
                unset($v['coordinates']);
            }
            return $this->success('success', compact('list'));
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }


    /**
     * 装备属性数组
     * @return false|string|\think\response\Json
     */
    public function careersEquipmentAttributes()
    {
        $this->equipment_attributes_model = new AhEquipmentAttributes();
        $data = input('post.');
        try {
            $where = [];
            if (isset($data['type']) && $data['type'] != '') {
                $where[] = ['type', '=', $data['type']];
            }

            $list = $this->changeData(
                $this->equipment_attributes_model->cache(true)->where($where)->select()->toArray(),
                ['create_time', 'icon']
            );
            $new_list = $this->groupType($this->equipment_attributes_model, $list);
            return $this->success('success', compact('new_list'));
        } catch (\Exception $exception) {
            return $this->error($exception);
        }

    }

    /**
     * 获取宝石接口
     * @return false|string|\think\response\Json
     */
    public function careersEquipmentGem()
    {
        $this->gemstone_model = new AhGemstone();
        $data = input('post.');
        try {
            $where = [];
            if (isset($data['type']) && $data['type'] != '') {
                $where[] = ['type', '=', $data['type']];
            }
            $list = $this->changeData(
                $this->gemstone_model->cache(true)->where($where)->select()->toArray(),
                ['create_time']
            );
            $new_list = $this->groupType($this->gemstone_model, $list);
            return $this->success('success', compact('new_list'));
        } catch (\Exception $exception) {
            return $this->error($exception);
        }
    }

    /**
     * 获取护符阶级图片和护符内容
     * @return false|string|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function careersAmulet()
    {
        $data = input('post.');
        try {
            $model = new SkzyCamp();
            $level_model = new AhAmuletLevel();
            $level = $this->changeData(
                $level_model->cache(true)->order('number')->select()->toArray(),
                ['create_time']
            );
            $where = [];
            if (isset($data['role_id']) && $data['role_id'] != '') {
                $where[] = ['role_id', '=', $data['role_id']];
            }
            $amulet = $this->changeData(
                $model->cache(true)->where($where)->select()->toArray(),
                ['create_time']
            );
            return $this->success('success', compact('level', 'amulet'));
        } catch (\Exception $exception) {
            return $this->error($exception);
        }

    }

    private function groupType($model, $list)
    {
        $new_list = [];
        foreach ($model->getTypeParam() as $k => $v) {
            foreach ($list as &$item) {
                if ($item['type'] == $k) {
                    $new_list[$v['name']][] = $item;
                }
                unset($item);
            }
            if (isset($new_list[$v['name']])) {
                $decode_data = [];
                if (isset($v["decode_data"])) $decode_data = $v['decode_data'];
                $new_list[$v['name']] = $this->changeData($new_list[$v['name']], $v['delete_data'], $decode_data);
            }
            if ($k == 3 && isset($new_list[$v['name']]) && $v['name'] = 'breach') {//突破伤害有搜索条件
                foreach ($new_list[$v['name']] as $item) {
                    $new_list['breach_kind'][$item['kind']] = [
                        'kind' => $item['kind'],
                        'kind_desc' => $item['kind_desc'],
                    ];
                }
                $new_list['breach_kind'] = array_values($new_list['breach_kind']);
            }
        }
        return $new_list;
    }

    public function changeData($data, $filter = [], $decode_data = [])
    {
        foreach ($data as &$v) {
            foreach ($filter as $item) {
                if (is_null($v[$item])) unset($v[$item]);
                if (isset($v[$item])) unset($v[$item]);
            }
            foreach ($decode_data as $item) {
                if (isset($v[$item])) $v[$item] = json_decode($v[$item], true);
            }
            $v['delete_time'] = 1;
            unset($v['delete_time']);
            if (isset($v['create_time'])) $v['create_time'] = date("Y-m-d", strtotime($v['create_time']));
        }
        return $data;
    }
}